package com.finger.gulimall.order.web;

import com.finger.gulimall.order.entity.vo.AddrFareVo;
import com.finger.gulimall.order.entity.vo.OrderConfirmVo;
import com.finger.gulimall.order.entity.vo.OrderSubmitVo;
import com.finger.gulimall.order.entity.vo.SubmitOrderRespVo;
import com.finger.gulimall.order.exception.NotStockException;
import com.finger.gulimall.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @ClassName OrderWebController
 * @Description TODO
 * @Author finger
 * @Date 2022/7/3 22:19
 * @Version 1.0
 */
@Controller
public class OrderWebController {

    @Autowired
    private OrderService orderService;


    /**
     * 确认订单
     * @return
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) throws Exception {
        OrderConfirmVo confirmVo = orderService.orderConfirmVo();
        model.addAttribute("orderConfirmVo", confirmVo);
        return "confirm";
    }

    /**
     * 计算运费
     * @return
     */
    @ResponseBody
    @GetMapping("/addrFare/{addrId}")
    public AddrFareVo addrFare(@PathVariable Long addrId) {
        return orderService.addrFare(addrId);
    }

    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes redirectAttributes) {


        try {

            SubmitOrderRespVo submitOrderRespVo = orderService.submitOrder(orderSubmitVo);

            switch (submitOrderRespVo.getCode()) {

                case 0:
                    model.addAttribute("submitOrderRespVo", submitOrderRespVo);
                    return "pay";

                case 1:
                    redirectAttributes.addFlashAttribute("msg", "请勿重复提交");
                    return "redirect:http://order.gulimall.com/toTrade";
                case 2:
                    redirectAttributes.addFlashAttribute("msg", "请重新检查商品价格");
                    return "redirect:http://order.gulimall.com/toTrade";
                default:
                    redirectAttributes.addFlashAttribute("msg", "系统出错");
                    return "redirect:/toTrade";
            }

        } catch (NotStockException e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("msg","请检查商品是否存在库存");
            return "redirect:http://order.gulimall.com/toTrade";
        }

    }
}
